package com.kexilo.core.common.config;

import com.kexilo.core.common.interceptor.ApiVersionInterceptor;
import com.kexilo.core.common.interceptor.RepeatSubmitInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * Web MVC配置
 * 
 * @author Kexilo
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    
    private static final Logger log = LoggerFactory.getLogger(WebMvcConfig.class);

    @Autowired
    private RepeatSubmitInterceptor repeatSubmitInterceptor;

    @Autowired
    private ApiVersionInterceptor apiVersionInterceptor;

    /**
     * 跨域配置
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*") // 允许的源
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的方法
                .allowedHeaders("*") // 允许的头
                .allowCredentials(true) // 允许凭证
                .maxAge(3600); // 预检请求的缓存时间（秒）
        
        log.info("CORS跨域配置完成");
    }

    /**
     * 静态资源映射
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 本地文件上传路径
        registry.addResourceHandler("/profile/**")
                .addResourceLocations("file:profile/");
        
        // 静态资源路径
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");
        
        // 文档资源路径
        registry.addResourceHandler("/docs/**")
                .addResourceLocations("classpath:/docs/");
                
        log.info("静态资源映射配置完成");
    }

    /**
     * 配置消息转换器
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 添加Jackson消息转换器，并设置为首选
        MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = 
            new MappingJackson2HttpMessageConverter();
        
        // 设置JSON转换的ObjectMapper（与JacksonConfig保持一致）
        jackson2HttpMessageConverter.setObjectMapper(JacksonConfig.createObjectMapper());
        
        // 添加到转换器列表的开头，使其具有更高的优先级
        converters.add(0, jackson2HttpMessageConverter);
        
        log.info("HTTP消息转换器配置完成");
    }

    /**
     * 拦截器配置
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // API版本控制拦截器
        registry.addInterceptor(apiVersionInterceptor)
                .addPathPatterns("/api/**")
                .order(1);
        
        // 重复提交拦截器
        registry.addInterceptor(repeatSubmitInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/auth/login", "/auth/logout", "/auth/captcha", 
                                   "/actuator/**", "/v3/api-docs/**", "/swagger-ui/**")
                .order(2);
        
        log.info("拦截器配置完成");
    }
}
